import axios from 'axios';
import type { AxiosRequestConfig,AxiosError } from 'axios';
import router from '@/router' // ✅ 正确导入路由实例
import { reactive } from 'vue'



// 定义接口响应格式
interface AuthResponse {
  code: number
  message: string
  data?: {
    token: string
    userInfo: {
      id: number
      username: string
      avatar: string
    }
  }
}

// 定义用户信息类型
export interface UserInfo {
  id: number
  username: string
  avatar: string
}

// 全局状态 (判断用户是否为登录状态)
export const authState = reactive({
  isLoggedIn: false,
  userInfo: null as UserInfo | null
})


// 创建axios实例
const authApi = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5000
})

// 请求拦截器 - 添加token
authApi.interceptors.request.use((config: AxiosRequestConfig) => {
  try {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers = {
        ...(config.headers || {}), // 确保 headers 存在
        Authorization: `Bearer ${token}`
      }
    }
  } catch (error) {
    console.error('localStorage is not available:', error)
  }
  return config
})

// 在auth.ts中增加错误状态码处理
// 响应拦截器 - 处理401未授权
authApi.interceptors.response.use(
  response => response,
  (error: AxiosError) => {
    const status = error.response?.status
    if (status === 401) {
      localStorage.removeItem('token')
      router.replace('/login')
    } else if (status && status >= 500) {
      console.error('服务器错误:', error)
    }
    return Promise.reject(error)
  }
)

// 登录接口
export const login = (params: { username: string; password: string }) => {
  return authApi.post<AuthResponse>('/api/auth/login', params).then(res => {
    if (res.data.code === 200 && res.data.data) {
      localStorage.setItem('token', res.data.data.token)
      localStorage.setItem('userInfo', JSON.stringify(res.data.data.userInfo))
      authState.isLoggedIn = true
      authState.userInfo = res.data.data.userInfo
    }
    return res
  })
}

// 注册接口  
export const register = (params: {
  username: string
  email: string
  password: string
}) => {
  return authApi.post<AuthResponse>('/api/auth/register', params).then(res => {
    if (res.data.code === 200 && res.data.data) {
      localStorage.setItem('token', res.data.data.token)
      localStorage.setItem('userInfo', JSON.stringify(res.data.data.userInfo))
    }
    return res
  })
}

// 退出登录
export const logout = () => {
  authState.isLoggedIn = false
  authState.userInfo = null
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
  router.push('/')
}

// 获取用户信息接口
export const getUserProfile = async (): Promise<UserInfo> => {
  try {
    const response = await authApi.get<AuthResponse>('/api/user/profile')
    if (response.data.code === 200 && response.data.data?.userInfo) {
      // 更新本地存储
      localStorage.setItem('userInfo', JSON.stringify(response.data.data.userInfo))
      return response.data.data.userInfo
    }
    throw new Error('获取用户信息失败')
  } catch (error) {
    // 统一处理401错误（已在拦截器中处理）
    throw error
  }
}

// 检查登录状态方法
export const checkAuthStatus = async () => {
  const token = localStorage.getItem('token')
  if (!token) {
    authState.isLoggedIn = false
    authState.userInfo = null
    return
  }
  try {
    // 优先尝试获取最新用户信息
    const userInfo = await getUserProfile()
    authState.isLoggedIn = true
    authState.userInfo = userInfo
  } catch (error) {
    authState.isLoggedIn = false
    authState.userInfo = null
  }
}

// // Mock拦截器
// authApi.interceptors.response.use((response) => {
//   if (response.config.url?.includes('/auth')) {
//     return {
//       ...response,
//       data: {
//         code: 200,
//         message: 'success',
//         data: {
//           token: 'mock-token',
//           userInfo: {
//             id: 1,
//             username: response.config.data?.username || 'testuser',
//             avatar: 'https://poetize.cn/static/avatar.png'
//           }
//         }
//       }
//     }
//   }
//   return response
// })
